import Taro from "@tarojs/taro";

let getSystemInfoResultCache:Taro.getSystemInfo.Result;
export async function getSystemInfo():Promise<[Taro.getSystemInfo.Result|undefined, Error|null]> {
  return new Promise<[Taro.getSystemInfo.Result|undefined, Error|null]>(resolve => {
    if (getSystemInfoResultCache) {
      resolve([getSystemInfoResultCache, null]);
      return ;
    }

    Taro.getSystemInfo({
      success:(res => {
        getSystemInfoResultCache = res;
        console.log("getSystemInfoResultCache", getSystemInfoResultCache);
        resolve([res, null])
      }),
      fail:(err => {
        resolve([undefined, new Error(err.message)])
      })
    })
  })
}

export async function nextTick():Promise<void> {
  return new Promise(resolve => {
    Taro.nextTick(() => {
      resolve();
    })
  })
}

export async function querySelectorClientRect (selector: string,):
  Promise<Taro.NodesRef.BoundingClientRectCallbackResult> {
  return new Promise(resolve => {
    const query = Taro.createSelectorQuery();
    query.select(selector)
      .boundingClientRect((res: Taro.NodesRef.BoundingClientRectCallbackResult) => {
        resolve(res)
      })
      .exec()
  });
}
